<template>
  <div class="container">
    <div class="container-top">
      <div class="logo-box">
        <div class="logo">
        </div>
        <div class="logo-txt">量准SPR数据云计算后台</div>

        <div
          class="logout-postion"
          @click="logout"
        >
          <svg-icon
            class="logout"
            icon-class="logout"
          />
        </div>
      </div>
    </div>

    <div class="text-center upload-box">
      <div>
        <el-upload
          ref="rebateUpload"
          class="upload-demo"
          drag
          :action="upload"
          name="excel"
          :limit="1"
          :before-upload="beforeUpload"
          :headers="headerUpload"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          :show-file-list="false"
          :on-error="handleError"
          v-show="isShowUpload"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <div class="upload-name-box">
          <div
            class="upload-name"
            v-show="isShowUploadtxt"
          >
            {{uploadFile.name}}
            <span @click="handleRemove">x</span>
          </div>
          <el-progress
            :percentage="percentage"
            :color="customColor"
            v-show="isShowPer"
          ></el-progress>
        </div>
      </div>
    </div>

    <div
      class="container-body"
      v-if="isShowStepOne"
    >

      <div class="title-space">
        <span>OD值：</span>
      </div>
      <table
        id="table-1"
        width="100%"
        v-for="(listItem,listIndex) in originalData"
      >

        <tr
          v-for="(table,key,index) in listItem"
          :key="index"
        >
          <td class="color-000">{{key!=='time'?key:'孔'}}</td>
          <td>
            <span v-if="key!=='time'">
              {{concentration[index]}}
            </span>
            <span
              class="color-000"
              v-else
            >
              待测物浓度(ug/ml)
            </span>
          </td>
          <td v-for="iTable in table">
            <span v-if="key!=='time'">{{iTable}}</span>
            <span
              class="color-000"
              v-else
            >{{iTable + 's'}}</span>
          </td>
        </tr>
      </table>

      <div class="title-space">
        <span>OD值相对变化率（%）：</span>
      </div>
      <table
        id="table-1"
        width="100%"
        v-for="(listItem,listIndex) in originalDataRate"
      >

        <tr
          v-for="(table,key,index) in listItem"
          :key="index"
        >
          <td class="color-000">{{key!=='time'?key:'孔'}}</td>
          <td>
            <span v-if="key!=='time'">
              {{concentration[index]}}
            </span>
            <span
              class="color-000"
              v-else
            >
              待测物浓度(ug/ml)
            </span>
          </td>
          <td v-for="iTable in table">
            <span v-if="key!=='time'">{{iTable}}</span>
            <span
              class="color-000"
              v-else
            >{{iTable + 's'}}</span>
          </td>
        </tr>
      </table>

      <div class="space text-center">
        <div
          class="chart"
          v-for="(chart,index) in allStepOneCharts"
        >
          <easyChart
            :id="'StepOne'+index"
            :data='chart'
          ></easyChart>
        </div>
      </div>

      <div class="space">
        <div class="title-space">
          <span>光强值：</span>
        </div>
        <table
          id="table-1"
          width="100%"
          v-for="lightValueItem in lightValue"
        >
          <tr
            v-for="(table,key,index) in lightValueItem"
            :key="index"
          >
            <td class="color-000">{{key!=='time'?key:'孔'}}</td>
            <td>
              <span v-if="key!=='time'">
                {{concentration[index]}}
              </span>
              <span
                class="color-000"
                v-else
              >
                待测物浓度(ug/ml)
              </span>
            </td>
            <td v-for="iTable in table">
              <span v-if="key!=='time'">{{iTable}}</span>
              <span
                class="color-000"
                v-else
              >{{iTable + 's'}}</span>
            </td>
          </tr>
        </table>
      </div>

      <div class="space">
        <div class="title-space">
          <span>光强相对变化率（%）： </span>
        </div>
        <table
          id="table-1"
          width="100%"
          v-for="lightRateItem in lightRate"
        >
          <tr
            v-for="(table,key,index) in lightRateItem"
            :key="index"
          >
            <td class="color-000">{{key!=='time'?key:'孔'}}</td>
            <td>
              <span v-if="key!=='time'">
                {{concentration[index]}}
              </span>
              <span
                class="color-000"
                v-else
              >
                待测物浓度(ug/ml)
              </span>
            </td>
            <td v-for="iTable in table">
              <span v-if="key!=='time'">{{iTable}}</span>
              <span
                class="color-000"
                v-else
              >{{iTable + 's'}}</span>
            </td>
          </tr>
        </table>
      </div>

      <div class="space text-center">
        <div
          class="chart"
          v-for="(chart,index) in allLightRateCharts"
        >
          <easyChart
            :id="'logLightRate'+index"
            :data='chart'
          ></easyChart>
        </div>
      </div>

      <div class="title-space">
        <span>计算结果：</span>
        <el-button
          type="text"
          @click="downloadExl()"
          size="mini"
        >导出表格</el-button>
      </div>

      <div class="title-space">
        <span>待测物分子量（Da）：</span>
        {{mole}}
      </div>

      <div
        class="space"
        v-show="isShowStepTwo"
      >
        <table
          id="table-1"
          width="100%"
          v-for="stepTwoItem in stepTwoList"
        >
          <tr
            v-for="(table,key,index) in stepTwoItem"
            :key="index"
          >
            <td class="color-000">
              <span v-if="key!=='time'">{{key}}</span>
              <span v-else>孔</span>
            </td>
            <td
              v-for="iTable in table"
              v-if="key ==='time'"
              class="color-000"
            >
              <span
                v-if="iTable==='ka'"
                v-html="equation1"
              > </span>
              <span
                v-else-if="iTable==='Kd'"
                v-html="equation2"
              > </span>
              <span
                v-else-if="iTable==='KD'"
                v-html="equation3"
              > </span>
              <span v-else>{{iTable}}</span>
            </td>
            <td
              v-for="iTable in table"
              v-if="key !=='time'"
            >
              {{iTable}}
            </td>
          </tr>
        </table>
      </div>
      <div class="space text-center">
      </div>
    </div>

    <!-- 截图曲线 -->
    <div
      class="m-top-fff"
      v-if="showScreenshotsImg"
    >
      <div
        class="chart"
        v-for="(chart,index) in allStepOneCharts"
      >
        <easyChart
          :id="'logStepOne'+index"
          :data='chart'
        ></easyChart>
      </div>
      <div
        class="chart"
        v-for="(chart,index) in allLightRateCharts"
      >
        <easyChart
          :id="'logLightRate'+index"
          :data='chart'
        ></easyChart>
      </div>
    </div>

    <el-dialog
      title="待测物数据"
      :visible.sync="isShowInputLog"
      :close-on-click-modal="false"
      :before-close="handleRemove"
      width="90%"
      top="5%"
      center
    >
      <div>
        <div class="title-space">
          <span>待测物浓度(ug/ml)</span>
        </div>
        <table
          id="table-1"
          width="100%"
          v-for="(listItem,listIndex) in originalData"
        >
          <tr>
            <td
              v-for="(table,key,index) in listItem"
              v-if="key!=='time'"
              width="50"
            >
              {{key}}
            </td>
          </tr>
          <tr>
            <td
              v-for="(table,key,index) in listItem"
              v-if="key!=='time'"
            >
              <el-input
                type="Number"
                v-model="concentration[index]"
              ></el-input>
            </td>
          </tr>
        </table>

        <div class="space text-center">
          <div class="title-space">
            <span>待测物分子量（Da）：</span>
            <el-input
              type="number"
              class="input"
              v-model="mole"
              style="width:500px;"
            >
            </el-input>
          </div>
        </div>

        <div class="space text-center">
          <!-- <el-button
            type="primary"
            @click="handleRemove()"
            size="small"
            class="btn-submit-color"
          >取消计算</el-button> -->
          <el-button
            type="primary"
            @click="handleCompute()"
            size="small"
            :loading="computeLoading"
            class="btn-submit-color"
          >提交计算</el-button>
        </div>

      </div>
    </el-dialog>

  </div>
</template>
<script>
import easyChart from "@/components/EasyChart";
import { fetchUploadStep2, fetchUploadExl } from "@/api/table";
import { setStore, getStore } from "@/utils/common";
import { getToken, removeToken } from "@/utils/auth";

export default {
  data() {
    return {
      originalData: [],
      originalDataRate: [],
      lightRate: [],
      lightValue: [],
      stepTwoList: [],
      computeLoading: false, //显示计算loading
      computeAllowed: true, //防连点
      isShowInputLog: false, //是否显示公式
      isShowStepOne: false, //是否显示第一步表格
      isShowStepTwo: false, //是否显示第二步表格
      isShowEchartsLightRateLog: false, //是否显示曲线
      isShowEchartsStepOneLog: false, //是否显示曲线
      showScreenshotsImg: true, //页面上的曲线隐藏
      isShowUpload: true,
      isShowUploadtxt: false,
      uploadFile: {},
      mole: "",
      concentration: [], //浓度
      trueConcentration: [],
      imgBase64Data: [], //转图片
      exlName: "", //下载表格名
      keyNum: 0, //孔数
      tableTop: [
        "待测物浓度(ug/ml)",
        "待测物饱和时光强变化率值",
        "拟合值a",
        "拟合值b",
        "ka",
        "Kd",
        "KD"
      ],
      tableSub: [],
      isShowPer: false,
      percentage: 0,
      customColor: "#e6a23c",
      allLightRateCharts: [],
      allStepOneCharts: [],
      equation1: "",
      equation2: "",
      equation3: ""
    };
  },
  components: {
    easyChart
  },
  mounted() {
    // this.handleSuccess();
  },
  methods: {
    goNext(route, type) {
      if (type === 1) {
        setStore("chartData", this.lightRate);
      }
      this.$router.push({ path: route });
    },
    beforeUpload(file) {
      this.uploadFile = file;
      this.isShowPer = true;
      this.isShowUpload = false;
      this.isShowUploadtxt = true;
      this.percentage += 60 + Math.floor(Math.random() * 10);
    },
    handleSuccess(file, filelist) {
      if (file.status === 200) {
        const next = 100 - this.percentage;
        this.percentage += next;
        setTimeout(() => {
          this.isShowPer = false;
        }, 1000);

        this.isShowInputLog = true;
        this.originalData = file.originalData;
        this.originalDataRate = file.originalDataRate;
        this.lightRate = file.lightRate;
        this.lightValue = file.lightValue;
        this.keyNum = 0;
        this.originalData.forEach((item, index) => {
          const arryRate = [];
          for (let i in item) {
            this.concentration.push("");
          }
        });
        setStore("uuid", file.uuid);
        this.keyNum = this.concentration.length - 1;
      } else {
        this.$message.error("发生错误请联系管理员");
      }
    },
    handleError() {
      this.$message.error("发生错误请联系管理员");
    },
    async handleCompute() {
      if (this.computeAllowed) {
        this.computeAllowed = false;
        this.computeLoading = true;
        this.trueConcentration = [];
        this.concentration.forEach(item => {
          if (item !== "" && item >= 0) {
            this.trueConcentration.push(item);
          }
        });
        this.drawChart();
        //浓度判断
        if (this.trueConcentration.length !== this.keyNum) {
          this.$message.error("待测物浓度格式输入错误，请输入数字");
          this.computeLoading = false;
          this.computeAllowed = true;
          return false;
        } else if (this.mole < 0) {
          this.$message.error("待测物分子量格式输入错误，请输入数字");
          this.computeLoading = false;
          this.computeAllowed = true;
          return false;
        }
        let info = await fetchUploadStep2({
          crpValue: this.trueConcentration,
          uuid: getStore("uuid"),
          mole: this.mole
        });

        if (info.status === 200) {
          this.imgBase64Data = [];
          this.originalData.forEach((item, index) => {
            this.imgBase64Data.push(getStore("logStepOne" + index));
            this.imgBase64Data.push(getStore("logLightRate" + index));
          });
          await fetchUploadExl({
            crpValue: this.trueConcentration,
            uuid: getStore("uuid"),
            mole: this.mole,
            imgBase64: this.imgBase64Data
          });
          this.isShowInputLog = false;
          this.isShowStepOne = true;
          this.isShowStepTwo = true;
          this.computeLoading = false;
          this.computeAllowed = true;
          this.equation1 = `K<sub>a</sub>(10<sup>${info.unit[0][4]}</sup>M<sup>-1</sup>S<sup>-1</sup>)`;
          this.equation2 = `K<sub>d</sub>(10<sup>${info.unit[0][5]}</sup>S<sup>-1</sup>)`;
          this.equation3 = `K<sub>D</sub>(10<sup>${info.unit[0][6]}</sup>M)`;
          let infoData = info.data;
          this.stepTwoList = [];
          info.data.forEach(item => {
            item.time = this.tableTop;
            //存入数组排序
            let arr = [];
            for (let key in item) {
              if (key === "time") {
                arr.unshift(key);
              } else {
                arr.push(key);
              }
            }
            //根据数组排序插入数据
            let newInfoData = {};
            for (let i in arr) {
              var itemKey = arr[i];
              newInfoData[itemKey] = item[itemKey];
            }
            this.stepTwoList.push(newInfoData);
          });
          this.exlName = info.fileName;
        } else {
          this.computeAllowed = true;
          this.$message.error(info.msg);
        }
      }
    },
    handleRemove() {
      this.$refs["rebateUpload"].clearFiles(); //清除文件
      //上传框
      this.isShowUpload = true;
      this.isShowUploadtxt = false;
      //可以计算
      this.computeAllowed = true;
      this.computeLoading = false;
      //上传进度条
      this.percentage = 0;
      //显示进度
      this.isShowPer = false;
      this.originalDataRate = [];
      this.originalData = [];
      this.stepTwoList = [];
      this.isShowStepOne = false;
      this.isShowStepTwo = false;
      this.concentration = [];
      this.trueConcentration = [];
      this.isShowInputLog = false;
      this.mole = "";
    },
    downloadExl() {
      if (this.isShowStepTwo) {
        const href = `${process.env.BASE_URL}receive/download/excel/${this.exlName}`;
        window.open(href, "_blank");
      }
    },
    opens() {
      setTimeout(() => {
        let triggerResize = new Event("resize");
        window.dispatchEvent(triggerResize);
      }, 0);
    },
    logout() {
      removeToken();
      this.$router.go("/");
    },
    drawChart() {
      this.allLightRateCharts = [];
      this.allStepOneCharts = [];
      this.lightRate.forEach((item, index, arry) => {
        let chartsOption = {
          title: {
            text: ""
          },
          animation: false,
          tooltip: {
            trigger: "axis"
          },
          legend: {
            data: []
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            containLabel: true
          },
          toolbox: {
            feature: {
              saveAsImage: {}
            }
          },
          xAxis: {
            type: "category",
            axisTick: {
              alignWithLabel: true
            },
            axisLine: {
              onZero: false
            },
            boundaryGap: false,
            data: []
          },
          yAxis: {
            type: "value"
          },
          series: []
        };
        chartsOption.series = [];
        chartsOption.xAxis.data = [];
        let num = 0;
        for (let i in item) {
          if (i !== "time") {
            let chartSeries = {
              name: `${this.trueConcentration[num]}ug/ml`,
              type: "line",
              smooth: true,
              showSymbol: false,
              hoverAnimation: false,
              data: item[i]
            };
            if (arry.length > 1) {
              chartsOption.title.text = "光强相对变化率曲线" + (index + 1);
            } else {
              chartsOption.title.text = "光强相对变化率曲线";
            }

            chartsOption.legend.data.push(
              `${this.trueConcentration[num]}ug/ml`
            );
            chartsOption.series.push(chartSeries);
            num++;
          } else {
            chartsOption.xAxis.data = item[i];
          }
        }
        this.allLightRateCharts.push(chartsOption);
      });
      this.originalDataRate.forEach((item, index, arry) => {
        let chartsOption = {
          title: {
            text: ""
          },
          animation: false,
          tooltip: {
            trigger: "axis"
          },
          legend: {
            data: []
          },
          grid: {
            left: "3%",
            right: "5%",
            bottom: "15%",
            containLabel: true
          },
          dataZoom: [
            {
              type: "slider",
              xAxisIndex: 0,
              filterMode: "empty"
            },
            {
              type: "slider",
              yAxisIndex: 0,
              filterMode: "empty"
            }
          ],
          toolbox: {
            feature: {
              saveAsImage: {}
            }
          },
          xAxis: {
            type: "category",
            axisTick: {
              alignWithLabel: true
            },
            boundaryGap: false,
            minInterval: 120,
            data: []
          },
          yAxis: {
            type: "value"
            // minInterval: 0.1
            // min: value => {
            //   return value.min;
            // }
          },
          series: []
        };
        chartsOption.series = [];
        chartsOption.xAxis.data = [];
        let num = 0;
        for (let i in item) {
          if (i !== "time") {
            let chartSeries = {
              name: `${this.trueConcentration[num]}ug/ml`,
              type: "line",
              smooth: true,
              showSymbol: false,
              hoverAnimation: false,
              data: item[i]
            };
            if (arry.length > 1) {
              chartsOption.title.text = "OD值相对变换率曲线" + (index + 1);
            } else {
              chartsOption.title.text = "OD值相对变换率曲线";
            }
            chartsOption.legend.data.push(
              `${this.trueConcentration[num]}ug/ml`
            );
            chartsOption.series.push(chartSeries);
            num++;
          } else {
            chartsOption.xAxis.data = item[i];
          }
        }
        this.allStepOneCharts.push(chartsOption);
      });

      let _this = this;
      setTimeout(() => {
        _this.showScreenshotsImg = false;
      }, 1500);
    }
  },
  computed: {
    upload: () => {
      return process.env.BASE_URL + "receive/upload/step1";
    },
    headerUpload: () => {
      const data = {};
      data.TOKEN = getToken();
      return data;
    }
  }
};
</script>
